package com.hsnn.medstgmini.base.std.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.std.model.HospInfoLog;
import com.hsnn.medstgmini.base.std.model.StdCompdrugprofile;
import com.hsnn.medstgmini.base.std.model.StdCompdrugprofileLog;
import com.hsnn.medstgmini.base.std.service.StdCompdrugprofileManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.ImgUtil;
import com.hsnn.medstgmini.util.Pagination;
import com.hsnn.medstgmini.util.ParseDate;
import com.hsnn.medstgmini.util.ParseNumber;

@Controller
@RequestMapping("/stdCompdrugprofile")
public class StdCompdrugprofileController {

	private static final Logger log = Logger.getLogger(StdHospInfoController.class);
	@Autowired
	private StdCompdrugprofileManager stdCompdrugprofileManager;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private HttpSession session;

	@RequestMapping("/list")
	public String toList(String prodId, String compId, String drugCode,
			String drugName, String form, String unit, String prodCompName) {
		request.setAttribute("prodId", prodId);
		request.setAttribute("compId", compId);

		request.setAttribute("drugCode", drugCode);
		request.setAttribute("drugName", ParseNumber.toMessyCode(drugName));
		request.setAttribute("form", ParseNumber.toMessyCode(form));
		request.setAttribute("unit", ParseNumber.toMessyCode(unit));
		request.setAttribute("prodCompName",
				ParseNumber.toMessyCode(prodCompName));
		return ("/base/std/compdrugprofile/list");
	}

	/**
	 * @category 获取产品资质列表
	 * @author 应晓川
	 * @date 2015年8月21日11:50:43
	 * @return
	 * @return Pagination
	 */
	@RequestMapping("/getStdCompdrugprofile")
	@ResponseBody
	public Pagination getStdCompdrugprofile() {
		Pagination page = new Pagination(request);
		page.getConditions().put("compId", request.getParameter("compId"));
		page.getConditions().put("prodId", request.getParameter("prodId"));
		return stdCompdrugprofileManager.getStdCompdrugprofileList(page);
	}

	/**
	 * @category 新增/修改产品资质
	 * @author 应晓川
	 * @date 2015年8月21日11:42:43
	 * @return
	 * @return Pagination
	 */
	@RequestMapping("/saveOrUpdateStdCompdrugprofile")
	@ResponseBody
	public Pagination saveOrUpdateStdCompdrugprofile(
			StdCompdrugprofile stdCompdrugprofile, MultipartFile licence) {
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		String compId = request.getParameter("compId");// 企业ID
		String prodId = request.getParameter("prodId");// 产品id
		FileOutputStream fos = null;
		try {
			List<StdCompdrugprofile> list = stdCompdrugprofileManager
					.getStdCompdrugprofileByName(stdCompdrugprofile
							.getProfileName());

			if (StringUtils.isNotBlank(stdCompdrugprofile.getCompprofileId())) {
				StdCompdrugprofile stdCompdrugprofileFromDb = (StdCompdrugprofile) stdCompdrugprofileManager
						.getUniquerResult(StdCompdrugprofile.class,
								"compprofileId",
								stdCompdrugprofile.getCompprofileId());
				if (stdCompdrugprofileFromDb != null) {
					if (list.size() == 0
							|| list.get(0)
									.getCompprofileId()
									.equals(stdCompdrugprofileFromDb
											.getCompprofileId())) {
						if (licence != null) {
							if (licence.getSize() > 3 * 1024 * 1024) {
								page.setSuccess(false);
								page.setMsg("产品资质图片不能大于3M！");
								return page;
							}
							String name = licence.getOriginalFilename();
							if (!ImgUtil.isImg(name)) {
								page.setSuccess(false);
								page.setMsg("请选择格式正确的图片，图片支持格式：gif, jpg, jpeg, png, bmp！");
								return page;
							}

							int index = name.lastIndexOf(".");
							String suffix = name.substring(index);
							name = ParseDate.parseWithNum(new Date())
									.toString() + suffix;
							String path = session.getServletContext()
									.getRealPath("/");
							path = path.replaceAll("\\\\", "/")
									+ "upload/licence/";

							String filename = path + name;
							File file = new File(filename);
							fos = new FileOutputStream(file);
							InputStream stream = licence.getInputStream();
							byte[] bytes = new byte[1024];
							int length = 0;
							while ((length = stream.read(bytes)) != -1) {
								fos.write(bytes, 0, length);
							}
							fos.flush();
							stream.close();
							stdCompdrugprofileFromDb
									.setProfilePicAddr("upload/licence/" + name);
							stdCompdrugprofileFromDb
									.setProfilePicShortcutAddr("upload/licence/"
											+ name);
						}
						stdCompdrugprofileFromDb
								.setProfileName(stdCompdrugprofile
										.getProfileName());
						stdCompdrugprofileFromDb.setProfileStarttime(DateUtil
								.parseDate(stdCompdrugprofile
										.getProfileStarttimeStr()));
						stdCompdrugprofileFromDb.setProfileEndtime(DateUtil
								.parseDate(stdCompdrugprofile
										.getProfileEndtimeStr()));
						stdCompdrugprofileFromDb.setRemarks(stdCompdrugprofile
								.getRemarks());
						stdCompdrugprofileFromDb.setUpdDatetime(new Date());
						stdCompdrugprofileFromDb.setUpdUser(user.getId());
						if (stdCompdrugprofileManager
								.update(stdCompdrugprofileFromDb)) {
							StdCompdrugprofileLog stdCompdrugprofileLog = new StdCompdrugprofileLog();
							BeanUtils.copyProperties(stdCompdrugprofileLog,
									stdCompdrugprofileFromDb);
							stdCompdrugprofileLog.setLogId(UUID.randomUUID()
									.toString());
							stdCompdrugprofileManager
									.save(stdCompdrugprofileLog);
							page.setMsg("操作成功");
							;
							page.setSuccess(true);
						}

					} else {
						page.setMsg("产品资质名称已被使用！");
						;
						page.setSuccess(false);
					}
				}
			} else {
				if (list.size() == 0)// 名称未重名
				{
					if (licence != null) {

						if (licence.getSize() > 3 * 1024 * 1024) {
							page.setSuccess(false);
							page.setMsg("产品资质不图片能大于3M！");
							return page;
						}
						String name = licence.getOriginalFilename();
						if (!ImgUtil.isImg(name)) {
							page.setSuccess(false);
							page.setMsg("请选择格式正确的资质图片，图片支持格式：gif, jpg, jpeg, png, bmp！");
							return page;
						}

						int index = name.lastIndexOf(".");
						String suffix = name.substring(index);
						name = ParseDate.parseWithNum(new Date()).toString()
								+ suffix;
						String path = session.getServletContext().getRealPath(
								"/");
						path = path.replaceAll("\\\\", "/") + "upload/licence/";

						String filename = path + name;
						File file = new File(filename);
						fos = new FileOutputStream(file);
						InputStream stream = licence.getInputStream();
						byte[] bytes = new byte[1024];
						int length = 0;
						while ((length = stream.read(bytes)) != -1) {
							fos.write(bytes, 0, length);
						}
						fos.flush();
						stream.close();

						stdCompdrugprofile.setCompprofileId(UUID.randomUUID()
								.toString());
						Long gg = System.currentTimeMillis();
						stdCompdrugprofile.setProfileCode("ZZ" + gg.toString());
						stdCompdrugprofile.setProfilePicAddr("upload/licence/"
								+ name);
						stdCompdrugprofile
								.setProfilePicShortcutAddr("upload/licence/"
										+ name);
						stdCompdrugprofile.setProfileStarttime(DateUtil
								.parseDate(stdCompdrugprofile
										.getProfileStarttimeStr()));
						stdCompdrugprofile.setProfileEndtime(DateUtil
								.parseDate(stdCompdrugprofile
										.getProfileEndtimeStr()));
						stdCompdrugprofile.setCompId(compId);
						stdCompdrugprofile.setCompProdId(prodId);
						stdCompdrugprofile
								.setStatus(Constants.STD_COMPDRUGPROFILE_STATUS_1);
						stdCompdrugprofile.setUpdUser(user.getId());
						stdCompdrugprofile.setUpdDatetime(new Date());
						if (stdCompdrugprofileManager.save(stdCompdrugprofile)) {
							StdCompdrugprofileLog stdCompdrugprofileLog = new StdCompdrugprofileLog();
							BeanUtils.copyProperties(stdCompdrugprofileLog,
									stdCompdrugprofile);
							stdCompdrugprofileLog.setLogId(UUID.randomUUID()
									.toString());
							stdCompdrugprofileManager
									.save(stdCompdrugprofileLog);
							page.setMsg("操作成功");
							;
							page.setSuccess(true);
						}
					} else {
						page.setSuccess(false);
						page.setMsg("请上传产品资质图片！");
						return page;
					}
				} else {
					page.setSuccess(false);
					page.setMsg("产品资质名称已被使用！");
					;
					return page;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return (page);
	}

	/**
	 * @category 停用启用
	 * @author 应晓川
	 * @date 2015年8月19日09:15:45
	 * @return
	 * @return Pagination
	 */
	@RequestMapping("/updateStdCompdrugprofileStatus")
	@ResponseBody
	public Pagination updateStdCompdrugprofileStatus(String compprofileId,
			String status) {
		Pagination page = new Pagination(request);
		SysUser user = (SysUser) request.getSession().getAttribute(
				Constants.USERINFO);
		try {
			StdCompdrugprofile stdCompdrugprofile = (StdCompdrugprofile) stdCompdrugprofileManager
					.getUniquerResult(StdCompdrugprofile.class,
							"compprofileId", compprofileId);
			if (stdCompdrugprofile != null) {
				stdCompdrugprofile.setStatus(ParseNumber.toShort(status));
				stdCompdrugprofile.setUpdDatetime(new Date());
				stdCompdrugprofile.setUpdUser(user.getId());
				if (stdCompdrugprofileManager.update(stdCompdrugprofile)) {
					StdCompdrugprofileLog stdCompdrugprofileLog = new StdCompdrugprofileLog();
					BeanUtils.copyProperties(stdCompdrugprofileLog,
							stdCompdrugprofile);
					stdCompdrugprofileLog
							.setLogId(UUID.randomUUID().toString());
					stdCompdrugprofileManager.saveLog(stdCompdrugprofileLog);
					page.setMsg("操作成功");
					page.setSuccess(true);
				}
			} else {
				page.setSuccess(false);
				page.setMsg("该对象不存在");
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * @category 去查看药物目录维护记录详情
	 * @author 应晓川
	 * @date 2015年8月19日08:41:15
	 * @return
	 * @return Pagination
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/toStdCompdrugprofileLogList")
	public String toStdCompdrugprofileLogList() throws UnsupportedEncodingException {
		request.setAttribute("compprofileId", request.getParameter("compprofileId"));
		request.setAttribute("profileCode", request.getParameter("profileCode"));
		/*request.setAttribute("profileName", request.getParameter("profileName"));	*/
		String profileName = new String(request.getParameter("profileName").getBytes("iso8859-1"),"utf-8");
		request.setAttribute("profileName", profileName);
	
		return "/base/std/compdrugprofile/listLog";
	}

	/**
	 * @category 获取药品资质维护记录数据
	 * @author 应晓川
	 * @date 2015年8月19日08:46:23
	 * @return
	 * @return Pagination
	 */
	@RequestMapping("/getStdCompdrugprofileLogList")
	@ResponseBody
	public Pagination getStdCompdrugprofileLogList() {
		Pagination page = new Pagination(request);
		String compprofileId = request.getParameter("compprofileId");
		try {
			if (StringUtils.isNotBlank(request.getParameter("startDate"))) {
				page.getConditions().put("startDate",
						request.getParameter("startDate"));
			}
			if (StringUtils.isNotBlank(request.getParameter("endDate"))) {
				page.getConditions().put("endDate",
						request.getParameter("endDate"));
			}
			page.getConditions().put("compprofileId", compprofileId);
			page = stdCompdrugprofileManager.getStdCompdrugprofileLogList(page);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return page;
	}

	/**
	 * @category 跳转维护记录详情
	 * @date 2015年9月28日
	 * @param compprofileId
	 * @return
	 */
	/*@RequestMapping("/toDrugProfileLogDetail")
	public String toDrugProfileLogDetail(Model model, String logId) {
		List<Map<String, Object>> list = stdCompdrugprofileManager.getDrugProfileLogDetail(logId);
		Map<String, Object> oldInfo = new HashMap<String, Object>();
		Map<String, Object> newInfo = new HashMap<String, Object>();
		
		if (list != null && !list.isEmpty()) {
			if (list.size() == 1) {
				newInfo = list.get(0);
			} else if (list.size() == 2) {
				oldInfo = list.get(1);
				newInfo = list.get(0);
			}
		}
		
		model.addAttribute("oldInfo", oldInfo);
		model.addAttribute("newInfo", newInfo);
		
		return "/base/std/compdrugprofile/drugProfileLogDetail";
	}*/
	@RequestMapping("/toDrugProfileLogDetail")
	public String hospInfoLogDetail(Model model, String logId) {
		 printParams();
		List<Map<String,Object>> list = stdCompdrugprofileManager.getDrugProfileLogDetail(logId);
		
		List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
		String[] cColunm = {"资质编码","资质名称","资质类型","有效期开始日期","有效期截止日期","状态","备注"};
		String[] eColunm = {"profileCode","profileName","profileType","profileStarttime","profileEndtime","status","remarks"};
		for(int i = 0;i<cColunm.length;i++){
			Map<String,Object> map =  new HashMap<String,Object>();
			map.put("colunm", cColunm[i]);//字段名
			map.put("after", !"status".equals(eColunm[i])?list.get(0).get(eColunm[i]):"1".equals(list.get(0).get(eColunm[i]).toString())?"启用":"停用");//修改后数据
			map.put("before", list.size()==1?null:!"status".equals(eColunm[i])?list.get(1).get(eColunm[i]):"1".equals(list.get(1).get(eColunm[i]).toString())?"启用":"停用");//修改前数据
			if(list.size()==1){
				map.put("red", "1");//是否变红加粗 1是 0 否
			}else{
				//判断修改后与修改前数据是否相等
				if(list.get(0).get(eColunm[i])!=null&&list.get(1).get(eColunm[i])!=null&&!list.get(0).get(eColunm[i]).toString().equals(list.get(1).get(eColunm[i]).toString())){
					map.put("red", "1");
				}else{
					map.put("red", "0");
				}
			}
			mapList.add(map);
		}
		for(int i = 0;i<mapList.size();i++){//把要变红的放在list前面
			if("1".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		for(int i = 0;i<mapList.size();i++){
			if("0".equals(mapList.get(i).get("red"))){
				dataList.add(mapList.get(i));
			}
		}
		request.setAttribute("dataList", dataList);
		request.setAttribute("list", list);
		
		return  "/base/std/compdrugprofile/drugProfileLogDetail";
	}
	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
}
